<template>
  <div>
    <div id="my-three"></div>
    <el-button>three</el-button>
    <canvas ref="canvas" id="canvas"></canvas>
    <div>
      <video class="video-js" id="my-video" ref="videoPlayerRef" @play="vplay"></video>
    </div>
    <button @click="cplay">cplay</button>
    <div id="xgsp"></div>
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, onUnmounted, ref } from "vue"
  import { cloneDeep } from 'lodash'

  import * as THREE from "three"
  import TWEEN from "@tweenjs/tween.js"
  import { OrbitControls } from "three/examples/jsm/controls/OrbitControls"
  import { GUI } from "three/examples/jsm/libs/lil-gui.module.min.js"
  import { CSS2DRenderer, CSS2DObject } from "three/examples/jsm/renderers/CSS2DRenderer"
  import { CSS3DRenderer, CSS3DObject } from "three/examples/jsm/renderers/CSS3DRenderer"
  import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer"
  import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass"
  import { OutlinePass } from "three/examples/jsm/postprocessing/OutlinePass"
  import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader"

  import videojs from "video.js"
  import "video.js/dist/video-js.css"
  import Player from "xgplayer"
  import "xgplayer/dist/index.min.css"
  import { pointPositions, zdDatas } from "@/assets/zdData-fyj"
  
  onMounted(() => {
    initThree()
    // switchMeshRender()
    createShape()
    shapeRennder()
    // cu()
    // cu2()
    // cu2Render()
    // webGlTest()
    // loadLeePerrySmith()
  })

  let scene: THREE.Scene
  let camera: THREE.PerspectiveCamera
  const width: number =  window.innerWidth
  // const width: number = document.getElementById("my-three")?.clientWidth || window.innerWidth
  const height: number = 600
  function initThree() {
    //创建一个三维场景
    scene = new THREE.Scene()
    //创建一个透视相机，窗口宽度，窗口高度
    camera = new THREE.PerspectiveCamera(50, width / height, 0.1, 1000)
    camera.position.set(150, 100, 100)
    //添加光源
    const ambient = new THREE.AmbientLight(0xffffff, 0.5)
    scene.add(ambient)
    //创建辅助坐标轴
    const axesHelper = new THREE.AxesHelper(1000)
    scene.add(axesHelper)
    scene.background = new THREE.Color("#88B9DD")
    createMesh()
    createGui()
    createClickEvent()
    createCSS2Tag(mesh)
    createCSS3Tag(mesh)
    createRender()
    createEffect(mesh)
    camera.lookAt(150, 0, 0)
  }
  
  // 创建一个普通立方体
  let mesh: THREE.Mesh
  function createMesh() {
    //创建一个物体（形状）
    const geometry = new THREE.BoxGeometry(50, 50, 100) //长宽高都是100的立方体
    //创建材质（外观）
    const material = new THREE.MeshLambertMaterial({
      color: 0x00ff00, //(绿色)
      transparent: true, //开启透明度
      opacity: 0.7, //设置透明度
    })
    //创建一个网格模型对象
    mesh = new THREE.Mesh(geometry, material) //网络模型对象Mesh
    mesh.position.set(-50, 20, -50)
    mesh.name = "nomalMesh"
    //把网格模型添加到三维场景
    scene.add(mesh)
  }
  
  // 添加gui
  function createGui() {
    const gui = new GUI()
    gui.add(mesh.position, "x", 0, 100).name("x轴方向").step(1)
    gui.add(mesh.position, "y", 0, 100)
    gui.add(mesh.position, "z", 0, 100)
    const obj = {
      bool: false,
    }
    gui.add(obj, "bool")
    .name("旋转动画")
    .onChange(function (value) {
        if (value) {
          switchMeshRender()
        } else {
          switchMeshRender()
          // cancelAnimationFrame(ani)
        }
      })
  }

  // 创建渲染器
  let composer: EffectComposer
  let WebGLRenderer: THREE.WebGLRenderer
  let CSS2Renderer: CSS2DRenderer
  let CSS3Renderer: CSS3DRenderer
  let controls: OrbitControls
  function createRender() {
    // css2渲染标签
    CSS2Renderer = new CSS2DRenderer()
    CSS2Renderer.setSize( width, height )
    CSS2Renderer.domElement.style.position = 'absolute'
    CSS2Renderer.domElement.style.top = '0px'
    CSS2Renderer.domElement.style.pointerEvents = 'none'
    document.getElementById("my-three")?.appendChild( CSS2Renderer.domElement )

    // css3渲染标签
    CSS3Renderer = new CSS3DRenderer()
    CSS3Renderer.setSize( width, height )
    CSS3Renderer.domElement.style.position = 'absolute'
    CSS3Renderer.domElement.style.top = '0px'
    document.getElementById("my-three")?.appendChild( CSS3Renderer.domElement )
    
    //webgl渲染界面
    WebGLRenderer = new THREE.WebGLRenderer()
    WebGLRenderer.setSize(width, height) //设置渲染区尺寸
    document.getElementById("my-three")?.appendChild(WebGLRenderer.domElement)
    
    // 相机控件
    controls = new OrbitControls(camera, CSS3Renderer.domElement)
    controls.target.set(150, 0, 0)
    controls.addEventListener("change", () => {
      // WebGLRenderer.render(scene, camera)
      composer.render()
      CSS2Renderer.render(scene, camera)
      CSS3Renderer.render(scene, camera)
    })
    
    // 缩放控制
    window.onresize = function () {
      // const windowWidth: number = window.innerWidth
      // const windowWidth: number = document.getElementById("my-three")?.clientWidth
      WebGLRenderer.setSize(window.innerWidth, height)
      CSS2Renderer.setSize( window.innerWidth, height )
      CSS3Renderer.setSize( window.innerWidth, height )
      camera.aspect = window.innerWidth / height
      camera.updateProjectionMatrix()
      // WebGLRenderer.render(scene, camera)
      composer.render()
      CSS2Renderer.render(scene, camera)
      CSS3Renderer.render(scene, camera)
    }
  }
  
  function createCSS2Tag(object: any, name = "测试名字css2") {
    const txtDiv = document.createElement( 'div' )
    txtDiv.className = 'label'
    txtDiv.innerHTML = `<div>
                            <div>标签</div>
                            <div>${name}</div>
                          </div>`
    txtDiv.style.backgroundColor = '#ffffff'

    const txtLabel = new CSS2DObject( txtDiv )
    txtLabel.position.set( 0, 0, 0 )
    txtLabel.layers.set( 0 )
    object.add( txtLabel )
  }

  function createCSS3Tag(object: any, name = "测试名字css3") {
    const txtDiv = document.createElement( 'div' )
    txtDiv.className = 'label'
    txtDiv.innerHTML = `<div>
                            <div>标签</div>
                            <div>${name}</div>
                          </div>`
    txtDiv.style.backgroundColor = '#ffffff'

    const txtLabel = new CSS3DObject( txtDiv )
    txtLabel.position.set( 0, 40, 0 )
    txtLabel.layers.set( 0 )
    txtLabel.scale.set(0.5,0.5,0.5)
    object.add( txtLabel )
  }

  // 创建点击效果
  function createClickEvent() {
    document.getElementById("my-three")?.addEventListener('click', event => {
      let raycaster = new THREE.Raycaster()
      let mouse = new THREE.Vector2()
      // 宽高要和当前画布宽高对应起来 不然点击坐标会错误
      // const marginLeft = 150
      // const marginTop = 60
      // const width = document.getElementById("my-three")?.clientWidth
      // const height = document.getElementById("my-three")?.clientHeight
      // mouse.x = ((event.clientX - marginLeft) / width) * 2 - 1
      // mouse.y = -((event.clientY - marginTop) / height) * 2 + 1
      
      mouse.x = ( event.offsetX / window.innerWidth ) * 2 - 1
      mouse.y = - ( event.offsetY / height ) * 2 + 1
      raycaster.setFromCamera(mouse, camera)

      const intersects = raycaster.intersectObjects(scene.children)
      // 根据它来判断点击的什么，length为0即没有点击到模型
      if (intersects.length > 0) {
        const tmpList = scene.children.filter(i => {
          return i.type === "Mesh" && i.name !== 'wow'
        })
        tmpList.forEach(i => {
          if (i.name !== intersects[0].object.geometry!.name) {
            i.material = new THREE.MeshBasicMaterial({ color: "ffffff" })
          }
        })
        // 旋转网格(mesh)
        intersects[0].object.rotation.x += 10 * Math.PI / 180
        intersects[0].object.rotation.y += 10 * Math.PI / 180
        intersects[0].object.rotation.z += 10 * Math.PI / 180
        intersects[0].object.material = new THREE.MeshBasicMaterial({
          color: "#FF00FF",
          transparent: true,
          opacity: 0.5,
        })
        composer.render()
      }
    })
  }
  
  function createEffect(object) {
    // 创建一个EffectComposer（效果组合器）对象，然后在该对象上添加后期处理通道。
    composer = new EffectComposer(WebGLRenderer)
    // 新建一个场景通道  为了覆盖到原来的场景上
    const renderPass = new RenderPass(scene, camera)
    composer.addPass(renderPass)
    
    // 物体边缘发光通道
    let outlinePass = new OutlinePass(new THREE.Vector2(window.innerWidth, height), scene, camera)
    outlinePass.selectedObjects = [object]
    outlinePass.visibleEdgeColor.set(0xCD7F32)
    outlinePass.edgeStrength = 5
    outlinePass.edgeThickness = 3
    outlinePass.pulsePeriod = 4
    outlinePass.visibleEdgeColor.set(parseInt("0x00ff00"))
    outlinePass.hiddenEdgeColor = new THREE.Color(0, 0, 0)
    composer.addPass(outlinePass)
  }
  
  // 根据点生成线
  // const pointsList: any = [
  //   { x: 15, y: 3, z: 0, idx: 0 },
  //   { x: 15, y: 0, z: 10, idx: 1 },
  //   { x: 20, y: 0, z: 0, idx: 2 },
  //   { x: 20, y: 0, z: 10, idx: 3 },
  //   { x: 30, y: 0, z: 0, idx: 4 },
  //   { x: 30, y: 0, z: 10, idx: 5 },
  //   { x: 40, y: 0, z: 0, idx: 6 },
  //   { x: 40, y: 0, z: 10, idx: 7 },
  // ]

  const pointsList: typeof pointPositions = pointPositions
  let cube: THREE.Mesh
  let cubeList: any = []
  let cubeListPos: any = []
  let oldCubeListPos: any
  function createShape() {
    pointsList.forEach(pos => {
      const cubeGeometry = new THREE.BoxGeometry(0.2, 0.4, 0.2)
      const cubeMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff })
      cube = new THREE.Mesh(cubeGeometry, cubeMaterial)
      cube.name = pos.idx.toString()
      // cube.position.copy(pos)
      cube.position.set(pos.x, pos.y, pos.z)
      // createCSS2Tag(cube, pos.idx)
      scene.add(cube)
      cubeList.push(cube)
      cubeListPos.push(cube.position)
    })
    oldCubeListPos = cloneDeep(cubeListPos)
  }
  
  let cubeLineMesh: THREE.Line
  let shapeMesh: THREE.Mesh
  let step = new Array(cubeList.length)
  for (let i = 0; i < cubeList.length; i++) {
    step[i] = 0
  }
  let frameStep = 0
  const freq = 1.049
  const speed = function(dz: number, frameStep: number): number {
    const zdFormula = 200 * dz * Math.cos( frameStep * (360/ freq) )
    return zdFormula
  }
  function shapeAnimation(zdList, frameStep) {
    // scene.remove(cubeLineMesh)
    scene.remove(shapeMesh)
    // cubeLineMesh.dispose()
    // shapeMesh.dispose()
    
    // let tween1 = new TWEEN.Tween(cubeList[0].position)
    // tween1.to({ y: 9 }, 2000)
    //
    // let tween2 = new TWEEN.Tween(cubeList[0].position)
    // tween2.to({ y: -99 }, 2000)
    // tween1.chain(tween2)
    // tween1.start()
    
    for(let i=0;i<cubeList.length;i++) {
      step[i] = speed(zdList[i].y, frameStep)
      // cubeList[i].position.y = step[i]

      const tween = new TWEEN.Tween(cubeList[i].position)
      tween.to({ y: step[i] }, 1000).start().easing(TWEEN.Easing.Back.Out)
      // tween.to({ y: step[i] }, 1000).start().easing(TWEEN.Easing.Quadratic.Out)
      
      // if (zdList[i] >= 0) {
      //   if (zdList[i] >= oldCubeListPos[i].y) {
      //     if (cubeList[i].position.y >= zdList[i]) {
      //       step[i] = -speed(zdList[i], frameStep)
      //     }
      //     if (cubeList[i].position.y <= oldCubeListPos[i].y) {
      //       step[i] = speed(zdList[i], frameStep)
      //     }
      //   } else {
      //     if (cubeList[i].position.y >= oldCubeListPos[i].y) {
      //       step[i] = -speed(zdList[i], frameStep)
      //     }
      //     if (cubeList[i].position.y <= zdList[i]) {
      //       step[i] = speed(zdList[i], frameStep)
      //     }
      //   }
      // } else {
      //   if (zdList[i] >= oldCubeListPos[i].y) {
      //     if (cubeList[i].position.y <= oldCubeListPos[i].y) {
      //       step[i] = speed(zdList[i], frameStep)
      //     }
      //     if (cubeList[i].position.y >= zdList[i]) {
      //       step[i] = -speed(zdList[i], frameStep)
      //     }
      //   } else {
      //     if (cubeList[i].position.y <= zdList[i]) {
      //       step[i] = speed(zdList[i], frameStep)
      //     }
      //     if (cubeList[i].position.y >= oldCubeListPos[i].y) {
      //       step[i] = -speed(zdList[i], frameStep)
      //     }
      //   }
      // }
    }

    // 线
    // const curve = new THREE.CatmullRomCurve3(
    //   cubeListPos // 直接绑定方块的position以便后续用方块调整曲线
    // )
    // curve.curveType = "chordal" // 曲线类型
    // curve.closed = true // 曲线是否闭合
    // const points = curve.getPoints(50) // 50等分获取曲线点数组
    // cubeLineMesh = new THREE.Line(
    //   new THREE.BufferGeometry().setFromPoints(points),
    //   new THREE.LineBasicMaterial({ color: 0xff00ff })
    // )
    // scene.add(cubeLineMesh)
    
    // 三角面
    const arr32: number[] = []
    cubeListPos.forEach(i => {
      arr32.push(i.x, i.y, i.z)
    })
    // 索引
    const index = _generateIdx2(pointsList)
    
    // 颜色的索引和颜色
    const colors = _generateColorIdx(pointsList)
    generateColor(colors)

    const shapeGeometry = new THREE.BufferGeometry()
    const shapeMaterial = new THREE.MeshBasicMaterial({
      vertexColors: true, 
      side: THREE.DoubleSide
    }) 
    shapeGeometry.setAttribute('position', new THREE.BufferAttribute( new Float32Array(arr32), 3 ))
    shapeGeometry.setIndex(index)
    shapeGeometry.setAttribute("color", new THREE.BufferAttribute( new Float32Array(colors), 3 ))
    shapeMesh = new THREE.Mesh(shapeGeometry, shapeMaterial)
    shapeMesh.name = "wow"
    scene.add(shapeMesh)
  }

  setInterval(() => {
    frameStep = frameStep + 1
  }, 1200)
  function shapeRennder() {
    const zdList = zdDatas
    
    // TWEEN.update()
    // shapeAnimation(zdList, frameStep)
    // composer.render()
    // requestAnimationFrame(shapeRennder)
    
    setInterval(() => {
      TWEEN.update()
      shapeAnimation(zdList, frameStep)
      composer.render()
    }, 1000)
  }
  // 生成索引 只能针对顺序index
  // 0-2-4
  // 1-3-5
  function _generateIdx(pointList) {
    const list: any[] = []
    for(let i=0;i<pointList.length;i++) {
      if (pointList.slice(i,i+3).length >= 3) {
        list.push(pointList.slice(i,i+3))
      }
    }
    const list2: number[] = []
    list.forEach(i => {
      i.forEach(j => {
        list2.push(j.idx)
      })
    })
    return list2
  }
  // 0-1-2
  // 3-4-5
  function _generateIdx2(pointList) {
    const list: number[] = []
    const len = pointList.length
    for(let i=0;i<len-2;i++) {
      if (i === 0) {
        list.push(i, i+1, len/2)
      } else if (i === 1) {
        list.push(i, len/2, len/2+1)
      } else if (i > 1 && i % 2 == 1) {
        list.push(i-(i/2-0.5), len/2+(i/2-0.5), len/2+(i/2+0.5))
      } else if (i > 1 && i % 2 == 0) {
        list.push(i-(i/2), i-(i/2-1), len/2+(i/2))
      }
    }
    return list
  }

  function generateColor(colors) {
    const arr: number[] = []
    cubeListPos.forEach(i => {
      arr.push(i.y)
    })
    const max = Math.max(...arr)
    const min = Math.min(...arr)
    const height = max - min
    const c1 = new THREE.Color(0x00ff00)
    const c2 = new THREE.Color(0xff0000)
    for(let i=0;i<cubeListPos.length;i++) {
      // const percent = (Math.abs(cubeListPos[i].y) - min - 0.4) / height
      // const c = c1.clone().lerp(c2, percent)
      // colors[i * 3] = c.r
      // colors[i * 3 + 1] = c.g
      // colors[i * 3 + 2] = c.b
      
      colors[i * 3] = Math.abs(cubeListPos[i].y)
      colors[i * 3 + 1] = 1 - Math.abs(cubeListPos[i].y) * 0.25
      colors[i * 3 + 2] = 0

      // colors[i * 3] = _normalizeValue(cubeListPos[i].y, max, min)
      // colors[i * 3 + 1] = 1 - _normalizeValue(cubeListPos[i].y, max, min) * 0.2
      // colors[i * 3 + 2] = 0
      
    }
  }

  // 把数字缩限至0-1
  function _normalizeValue(val: number, max: number, min: number): number {
    const normalizedValue = (val - min) / (max - min)
    return normalizedValue
  }
  
  function _generateColorIdx(pointList) {
    const list: number[] = []
    const len = pointList.length
    for(let i=0;i<len;i++) {
      list[i * 3] = 0
      list[i * 3 + 1] = 1
      list[i * 3 + 2] = 0
    }
    return list
  }

  // 抖动点
  const iniArr = [
    0, 0, 0,
    0.5, 0, 0,
    0.8, 0, 0,
    1.9, 0, 0,
    3, 0, 0,
    4, 0, 0,
    5, 0, 0,
    6, 0, 0, 7,
    0, 0, 8,
    0, 0, 9,
    0, 0, 10,
    0, 0, 11,
    0, 0, 12,
    0, 0, 13,
    0, 0, 0,
    0, 12, 0.5,
    0, 12, 0.8,
    0, 12, 1.9,
    0, 12, 3,
    0, 12, 4,
    0, 12, 5,
    0, 12, 6,
    0, 12, 7,
    0, 12, 8,
    0, 12, 9,
    0, 12, 10,
    0, 12, 11,
    0, 12, 12,
    0, 12,
  ]
  function cu() {
    //创建一个空的几何体对象
    const geometry = new THREE.BufferGeometry()
    //类型化数组创建顶点数据
    const vertices = new Float32Array(iniArr)
    // 创建属性缓冲区对象
    // 3个为一组，表示一个顶点的xyz坐标设置几何体attributes属性的位置属性
    const geometryaee = new THREE.BufferAttribute(vertices, 3)
    geometry.setAttribute("position", geometryaee)
    // 点渲染模式
    const material = new THREE.PointsMaterial({
      color: 0xff0000,
      size: 2.0, //点对象像素尺寸
    })
    const points = new THREE.Points(geometry, material) //点模型对象
    scene.add(points)

    setInterval(() => {
      geometryaee.needsUpdate = true
      let geoList = points.geometry.attributes.position.array
      for (let i = 0; i < geoList.length; i++) {
        geoList[3 * i + 1] = Math.random() * 0.1 - 0.05
      }
      WebGLRenderer.render(scene, camera)
    }, 500)

    // 线材质对象
    // const material = new THREE.LineBasicMaterial({
    //   color: 0xff0000 //线条颜色
    // })
    // // 创建线模型对象
    // const cubeLineMesh = new THREE.Line(geometry, material)
    // scene.add(cubeLineMesh)

    // 三角
    // const material = new THREE.MeshBasicMaterial({
    //   color: 0xff00ff, //材质颜色
    //   side: THREE.DoubleSide, //默认只有正面可见
    // })
    // const mesh = new THREE.Mesh(geometry, material)
    // scene.add(mesh)
  }

  // 抖动立方体
  let cubeCu2: THREE.Mesh
  let cubeCu2List: any[]
  const iniArr2 = [
    { x: 0, y: 0, z: 0 },
    { x: 0.5, Y: 0, z: 0 },
    { x: 0.8, y: 0, z: 0 },
    { x: 1.9, y: 0, z: 0 },
    { x: 3, y: 0, z: 0 },
    { x: 4, y: 0, z: 0 },
    { x: 5, y: 0, z: 0 },
    { x: 6, y: 0, z: 0 },
    { x: 7, y: 0, z: 0 },
    { x: 8, y: 0, z: 0 },
    { x: 9, y: 0, z: 0 },
    { x: 10, y: 0, z: 0 },
    { x: 11, y: 0, z: 0 },
    { x: 12, y: 0, z: 0 },
    { x: 13, y: 0, z: 0 },
    { x: 0, y: 0, z: 12 },
    { x: 0.5, y: 0, z: 12 },
    { x: 0.8, y: 0, z: 12 },
    { x: 1.9, y: 0, z: 12 },
    { x: 3, y: 0, z: 12 },
    { x: 4, y: 0, z: 12 },
    { x: 5, y: 0, z: 12 },
    { x: 6, y: 0, z: 12 },
    { x: 7, y: 0, z: 12 },
    { x: 8, y: 0, z: 12 },
    { x: 9, y: 0, z: 12 },
    { x: 10, y: 0, z: 12 },
    { x: 11, y: 0, z: 12 },
    { x: 12, y: 0, z: 12 },
    { x: 13, y: 0, z: 12 },
  ]
  function cu2() {
    iniArr2.forEach(pos => {
      const geometry = new THREE.BoxGeometry(1, 0.2, 12)
      const material = new THREE.MeshLambertMaterial({
        wireframe: false,
        color: 0x0cb5e9,
        transparent: true, //开启透明度
        opacity: 0.6, //设置透明度
      })
      cubeCu2 = new THREE.Mesh(geometry, material)
      cubeCu2.position.copy(pos)
      scene.add(cubeCu2)
      cubeCu2List.push(cubeCu2)
    })
  }
  function cu2Animation() {
    for(let i=0;i<cubeCu2List.length;i++) {
      const randomNum = Math.random() * 0.2 - 0.1
      const tween = new TWEEN.Tween(cubeCu2List[i].position)
      tween.to({ y: randomNum }, 500)
      tween.start()
      const tween2 = new TWEEN.Tween(cubeCu2List[i].rotation)
      tween2.to({ z: randomNum }, 500)
      tween2.start()
      const tween3 = new TWEEN.Tween(cubeCu2List[i].material)
      if (randomNum < -0.09) {
        tween3.to({ color: new THREE.Color(0xe92421 - randomNum) }, 500)
        tween3.start()
      } else if (-0.09 < randomNum && randomNum < -0.07) {
        tween3.to({ color: new THREE.Color(0xff7119) }, 500)
        tween3.start()
      } else if (-0.07 < randomNum && randomNum < 0.07){
        tween3.to({ color: new THREE.Color(0x0cb5e9) }, 500)
        tween3.start()
      } else if (0.07 < randomNum && randomNum < 0.09) {
        tween3.to({ color: new THREE.Color(0xff7119) }, 500)
        tween3.start()
      } else {
        tween3.to({ color: new THREE.Color(0xe92421 + randomNum) }, 500)
        tween3.start()
      }
    }
  }
  function cu2Render() {
    requestAnimationFrame(cu2Render)
    WebGLRenderer.render( scene, camera )
    TWEEN.update()
    cu2Animation()
  }

  // 渲染动画函数
  let switchBtn = true
  let ani: any
  function switchMeshRender() {
    const tween = new TWEEN.Tween(mesh.position)
    if (switchBtn) {
      tween.to({ y: 1 }, 500)
      tween.start()
      switchBtn = false
    } else {
      tween.to({ y: 100 }, 500)
      tween.start()
      switchBtn = true
    }
    ani = requestAnimationFrame(render)
    composer.render()
    TWEEN.update()
  }
  
  // 编辑着色器
  function webGlTest() {
    let canvas = document.getElementById('canvas') as HTMLCanvasElement
    // 设置canvas宽高
    canvas.width = window.innerWidth
    canvas.height = window.innerHeight
    // 获取webgl绘图上下文
    const gl = canvas.getContext('webgl')
    if (!gl) {
      throw new Error('WebGL not supported')
    }
    
    // 第一次创建webgl绘图上下文时，需要设置窗口大小
    gl.viewport(0, 0, canvas.width, canvas.height)
    // 创建顶点着色器
    const vertexShader = gl.createShader(gl.VERTEX_SHADER)!
    // 创建顶点着色器的代码GLSL
    gl.shaderSource(vertexShader, `
			attribute vec4 a_Position;
			void main() {
				gl_Position = a_Position;
			}
		`)
    // 编译顶点着色器
    gl.compileShader(vertexShader)
    if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
      console.error(gl.getShaderInfoLog(vertexShader))
      throw new Error('could not compile vertexShader')
    }
    // 创建片元着色器
    const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER)!
    // 创建片元着色器的代码GLSL
    gl.shaderSource(fragmentShader, `
			void main(){
				gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
			}
		`)
    // 编译片元着色器
    gl.compileShader(fragmentShader)
    if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
      console.error(gl.getShaderInfoLog(fragmentShader))
      throw new Error('could not compile fragmentShader')
    }

    // 创建程序
    const program = gl.createProgram()!
    // 程序关联顶点着色器和片元着色器
    gl.attachShader(program, vertexShader)
    gl.attachShader(program, fragmentShader)
    // 链接程序
    gl.linkProgram(program)

    // 使用程序进行渲染
    gl.useProgram(program)
    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
      console.log(gl.getProgramInfoLog(program))
      throw new Error('could not link shaders')
    }

    // 创建顶点缓冲区对象
    let vertexBuffer = gl.createBuffer()
    // 绑定顶点缓冲区对象
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer)
    // 向顶点缓冲区对象写入数据
    let vertices = new Float32Array([
      0.0, 0.5, // 顶点着色器补全为（0.0，0.5，0.0，1.0）
      -0.5, -0.5,
      0.5, -0.5
    ])
    gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW)
    // 获取顶点着色器中a_Position变量的位置
    const a_Position = gl.getAttribLocation(program, 'a_Position')
    // 顶点缓冲区对象分配给a_Position变量
    gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0)
    // 启用顶点着色器的a_Position变量
    gl.enableVertexAttribArray(a_Position)
    // 绘制三角形
    gl.drawArrays(gl.TRIANGLES, 0, 3)
  }
  
  // 引入模型
  function loadLeePerrySmith() {
    const loader = new GLTFLoader()
    let mesh: any
    loader.load( '/src/assets/LeePerrySmith/LeePerrySmith.glb', function ( gltf ) {
      mesh = gltf.scene.children[ 0 ]
      mesh.material = new THREE.MeshPhongMaterial({
        specular: 0x111111,
        shininess: 25
      })

      scene.add( mesh )
      mesh.position.set( 100, 10, 10 )
      mesh.scale.set( 10, 10, 10 )
    })
  }

  // video
  onMounted(() => {
    setTimeout(() => {
      initVideo()
      initXg()
    }, 300)
  })

  onUnmounted(() => {
    if (myPlayer.value) {
      myPlayer.value.dispose()
    }
  })
  
  const videoPlayerRef = ref()
  const myPlayer = ref()
  function initVideo() {
    const options = {
      poster: "//vjs.zencdn.net/v/oceans.png",
      controls: true,
      sources: [
        {
          src: "//vjs.zencdn.net/v/oceans.mp4",
          type: "video/mp4",
        },
      ],
      controlBar: {
        remainingTimeDisplay: {
          displayNegative: false,
        },
      },
      playbackRates: [0.5, 1, 1.5, 2],
    }
    myPlayer.value = videojs(videoPlayerRef.value, options, () => {
      console.log("vedio点击")
    })
    myPlayer.value.on("timeupdate", function (event) {
      this.currentTime()
    })
  }

  function initXg() {
    let player = new Player({
      id: "xgsp",
      url: "//vjs.zencdn.net/v/oceans.mp4",
      volume: 0.6,
      autoplay: false,
      videoInit: true,
      lang: "zh-cn",
    })
  }

  const viRef = ref()
  function vplay(e) {
    console.log(e)
  }

  function cplay() {
    videoPlayerRef.value.play()
    viRef.value.play()
  }
</script>

<style>
  body {
    margin: 0;
    padding: 0;
  }
  #my-three canvas {
    //width: 100% !important;
    //height: 600px !important;
  }
  .video-js {
  }
  .video-js .vjs-big-play-button {
    font-size: 2.5em !important;
    cubeLineMesh-height: 2.3em !important;
    height: 2.5em !important;
    width: 2.5em !important;
    -webkit-border-radius: 2.5em !important;
    -moz-border-radius: 2.5em !important;
    border-radius: 2.5em !important;
    background-color: #73859f;
    background-color: rgba(115, 133, 159, 0.5) !important;
    border-width: 0.15em !important;
    margin-top: -1.25em !important;
    margin-left: -1.75em !important;
  }
  .vjs-big-play-button .vjs-icon-placeholder {
    font-size: 1.63em !important;
  }
</style>